package alo.p4.work;

import java.util.EmptyStackException;

//用一个数组实现两个栈
//保证只有数组有剩余空间，栈操作就不能提示异常
public class ArrayWithTwoStacks {
    private int[] dataArray;
    private int size;
    private int topOne;
    private int topTwo;
    public ArrayWithTwoStacks(int size){
        if (size<2) throw new IllegalStateException("size<2 is no persmissible");
        dataArray=new int[size];
        this.size=size;
        topOne=1;
        topTwo=size;
    }
    public void push(int stackId,int data){
        if (topTwo==topOne+1) throw new StackOverflowError("Array is full");
        if (stackId==1){
            dataArray[++topOne]=data;
        }else if (stackId==2){
            dataArray[--topTwo]=data;
        }else return;
    }
    public int pop(int stackId){
        if (stackId==1){
            if (topOne==-1) throw new EmptyStackException();
            int toPop= dataArray[topOne];
            dataArray[topOne--]= Integer.parseInt(null);
            return toPop;
        }else if (stackId==2){
            if (topTwo==this.size) throw new EmptyStackException();
            int toPop= dataArray[topTwo];
            dataArray[topTwo++]= Integer.parseInt(null);
            return toPop;
        }else return Integer.parseInt(null);
    }
    public int top(int stackId){
        if (stackId==1){
            if (topOne==-1) throw new EmptyStackException();
                return dataArray[topOne];
        }else if (stackId==2){
            if (topTwo==this.size) throw new EmptyStackException();
            return dataArray[topTwo];
        }else return Integer.parseInt(null);
    }
    public boolean isEmpty(int stackId){
        if (stackId==1){
            return topOne==-1;
        }else if (stackId==2) {
            return topTwo == this.size;
        }else return true;
    }
}
